from PyQt5.QtCore import Qt,QEvent,QTime
from PyQt5.QtWidgets import QMainWindow, QWidget,QApplication, QMessageBox,QSystemTrayIcon,QMenu, QAction
from PyQt5.QtGui import QPixmap,QIcon,QGuiApplication
# from qt_material import apply_stylesheet
import qdarkstyle
# from pyqt5Custom import StyledButton
from datetime import datetime  # 导入 datetime 库
import sys  # 导入 sys 库
import time  # 导入 time 库

from package.ui.QT_MainWindow import Ui_MainWindow  # 导入Ui_MainWindow类(QT设计师创建)
from package.Utils.task import myghostwinthread
from package.Utils.User_Thread import mytimethread
from package.Utils.log import logger,mylog  # 导入 logger 对象(python代码)
from package.Utils.Screen import screen   # 导入 screen 对象(python代码)
from package.Utils.config import config_obj  # 导入 config_obj 对象(python代码)
from package.Utils.cmd import CMD_Enable  # 导入 CMD_Enable 函数(python代码)

#图片路径
# img_relative_path = './image/icon/'
img_relative_path = 'D:/MyFile/Python_Code/Ghost_Window/Source/image/icon/'
class MyWinUtils:
    def __init__(self):
        self.img = f'{img_relative_path}Genshin.jpg'
        self.img_index = 0
        self.pix = 0
        self.click_button4_Flag = False  # 初始化点击 pushButton_4 标志位
        self.click_radioButton_Index = 1  # 初始化点击 radioButton 索引
        self.Shortcut_key = config_obj.config_text['HotKey']  # 初始化快捷键
        if len(config_obj.config_text['HotKey'].split('+',1)) > 1:
            self.Shortcut_key_list = config_obj.config_text['HotKey'].split('+',1)[0:2]  # 初始化键盘快捷键列表
            self.Shortcut_key_list[1] = self.Shortcut_key_list[1].lower()
        else:
            self.Shortcut_key_list = []  # 初始化键盘快捷键列表
        self.hwnd = config_obj.config_text['hwnd'] # 初始化窗口句柄

        self.Time_H = config_obj.config_text['Time_H']  # 初始化时间变量
        self.Time_M = config_obj.config_text['Time_M']  # 初始化时间变量
        self.time_msg = config_obj.config_text['Time_MSG']   # 初始化时间提示信息

        self.window_hwnd_States = True  # 初始化窗口状态(显示或隐藏)
        self.isrun = False  # 初始化运行标志位

        mytimethread.Start()  # 启动线程

mywinutils = MyWinUtils()

class MyMainWindow(QMainWindow, Ui_MainWindow,QMessageBox): # 继承 QMainWindow类和 Ui_MainWindow界面类
    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__(parent)  # 初始化父类
        self.setupUi(self)  # 继承 Ui_MainWindow 界面类

        self.init_tray()

        self.setWindowFlags(Qt.WindowStaysOnTopHint)  # 窗口置顶

    def init_tray(self):
        # 创建托盘图标
        self.tray_icon  = QSystemTrayIcon(self)
        self.tray_icon.setIcon(QGuiApplication.windowIcon())
        self.tray_icon.setIcon(QIcon(f'{img_relative_path}Genshin.jpg'))

        # 创建右键菜单
        tray_menu = QMenu()
        restore_action = QAction("恢复窗口", self)
        quit_action = QAction("退出程序", self)
        restore_action.triggered.connect(self.show_normal)
        quit_action.triggered.connect(self.quit_app)

        tray_menu.addAction(restore_action)
        tray_menu.addAction(quit_action)
        self.tray_icon.setContextMenu(tray_menu)

        # 绑定点击事件
        self.tray_icon.activated.connect(self.tray_icon_clicked)
        self.tray_icon.show()

    def show_normal(self):
        """从托盘恢复窗口"""
        self.showNormal()
        self.activateWindow()
        # self.tray_icon.hide()

    def quit_app(self):
        """安全退出程序"""
        self.tray_icon.hide()
        QApplication.quit()

    def tray_icon_clicked(self, reason):
        """处理托盘图标点击逻辑"""
        if reason == QSystemTrayIcon.DoubleClick:
            self.show_normal()

    def changeEvent(self, event):
        """拦截窗口状态变化事件"""
        if event.type()  == QEvent.WindowStateChange:
            if self.windowState()  & Qt.WindowMinimized:
                # self.tray_icon.show()  # 显示托盘图标
                self.hide()   # 最小化时隐藏主窗口
        super().changeEvent(event)

    # def closeEvent(self, event):
    #     """重写关闭事件（点击X按钮时隐藏到托盘）"""
    #     event.ignore()
    #     self.tray_icon.show()  # 显示托盘图标
    #     self.hide()



    #单击 基础设置 动作
    def BasicSet_Action(self):
        if mylog.log_enabled is True:
            logger.info('启动BasicSet窗口')
        if mywinutils.Shortcut_key != '':
            mybasicsetwin.lineEdit.setText(mywinutils.Shortcut_key)  # 设置快捷键输入框初始值
        if mywinutils.hwnd != 0:
            mybasicsetwin.lineEdit_hwnd.setText(str(mywinutils.hwnd))  # 设置窗口句柄输入框初始值

        mybasicsetwin.show()  # 显示BasicSet窗口

    #单击 高级设置 按钮
    def AdvancedSet_Action(self):
        if mylog.log_enabled is True:
            logger.info('启动AdvancedSet窗口')
        myAdvancedsetwin.time = QTime(mywinutils.Time_H, mywinutils.Time_M)  # 设置时间
        myAdvancedsetwin.timeEdit.setTime(myAdvancedsetwin.time)  # 设置时间输入框初始值
        myAdvancedsetwin.lineEdit_time_msg.setText(mywinutils.time_msg)  # 设置时间提示信息输入框初始值
        myAdvancedsetwin.show()  # 显示AdvancedSet窗口

    #单击 开始 按钮
    def click_pushButton_Start(self):
        mywinutils.isrun = True  # 运行标志位置为True
        self.window_hwnd_States = True  # 初始化窗口状态(显示)
        if mylog.log_enabled is True:
            logger.info('开始运行')
        self.actionBasicSet.setEnabled(False)  # 禁用基础设置按钮
        self.actionAdvancedSet.setEnabled(False)  # 禁用高级设置按钮
        self.pushButton_Start.setEnabled(False)  # 禁用开始按钮
        self.pushButton_Stop.setEnabled(True)  # 启用停止按钮
        self.pushButton_Start.setText('正在运行')  # 更改开始按钮文字
        self.msg = QMessageBox(self)  # 创建 QMessageBox 对象
        self.msg.setIconPixmap(QPixmap(mywinutils.img).scaled(64,64))
        self.msg.setWindowTitle('提示')
        self.msg.setText('原神，启动！')
        self.msg.setStandardButtons(QMessageBox.Yes)
        self.msg.show()  # 显示提示框
        myghostwinthread.Start()  # 启动线程
        # self.msg.information(self, '提示', '原神，启动！', QMessageBox.Yes)
        # time.sleep(4)
        # screen.Use_Shortcut(mywinutils.Shortcut_key)

    #单击 停止 按钮
    def click_pushButton_Stop(self):
        mywinutils.isrun = False  # 运行标志位置为False
        if mylog.log_enabled is True:
            logger.info('停止运行')
        self.actionBasicSet.setEnabled(True)  # 启用基础设置按钮
        self.actionAdvancedSet.setEnabled(True)  # 启用高级设置按钮
        self.pushButton_Start.setEnabled(True)  # 禁用停止按钮
        self.pushButton_Stop.setEnabled(False)  # 启用开始按钮
        self.pushButton_Start.setText('启动')  # 更改开始按钮文字

    #单击 Hide Me 按钮
    def click_pushButton_HideMe(self):
        # self.tray_icon.show()  # 显示托盘图标
        self.hide()

    #单击 窗口标题栏隐藏 按钮
    def click_checkBox_Hide(self):
        if mywinutils.hwnd != 0:
            try:
                if self.checkBox_Hide.isChecked():  #隐藏
                    screen.control_window_title(mywinutils.hwnd, 'hide')
                    if mylog.log_enabled is True:
                        logger.info('窗口标题栏已隐藏')
                else:                               #显示
                    screen.control_window_title(mywinutils.hwnd, 'show')
                    if mylog.log_enabled is True:
                        logger.info('窗口标题栏已显示')
            except:
                self.information(self, '警告', '没找到指定的窗口句柄！', QMessageBox.Yes)
        else:
            self.information(self, '警告', '请先设置窗口句柄！', QMessageBox.Yes)
            if mylog.log_enabled is True:
                logger.info('请先设置窗口句柄！')

    #单击 窗口滚动栏隐藏 按钮
    def click_checkBox_Scrollbar_Hide(self):
        if mywinutils.hwnd != 0:
            try:
                if self.checkBox_Scrollbar_Hide.isChecked():  #隐藏
                    screen.control_window_scrollbar(mywinutils.hwnd, 'hide')
                    if mylog.log_enabled is True:
                        logger.info('窗口滚动栏已隐藏')
                else:                               #显示
                    screen.control_window_scrollbar(mywinutils.hwnd, 'show')
                    if mylog.log_enabled is True:
                        logger.info('窗口滚动栏已显示')
            except:
                self.information(self, '警告', '没找到指定的窗口句柄！', QMessageBox.Yes)
        else:
            self.information(self, '警告', '请先设置窗口句柄！', QMessageBox.Yes)
            if mylog.log_enabled is True:
                logger.info('请先设置窗口句柄！')

    #单击 控制台显隐 按钮
    def click_checkBox_CMD_EN(self):
        if self.checkBox_CMD_EN.isChecked():
            CMD_Enable(1)  # 开启控制台
            if mylog.log_enabled is True:
                logger.info('控制台已开启')
        else:
            CMD_Enable(0)  # 关闭控制台
            if mylog.log_enabled is True:
                logger.info('控制台已关闭')

app = QApplication(sys.argv)  # 在 QApplication 方法中使用，创建应用程序对象
myWin = MyMainWindow()  # 实例化 MyMainWindow 类，创建主窗口
# apply_stylesheet(app, theme='light_teal.xml')
# setup stylesheet
app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
# or in new API
app.setStyleSheet(qdarkstyle.load_stylesheet(qt_api='pyqt5'))


from package.Utils.BasicSetWindow import MyBasicSetWindow  # 导入 MyBasicSetWindow 类(python代码)
mybasicsetwin = MyBasicSetWindow()  # 实例化 MyBasicSetWindow 类，创建MyBasicSetWindow窗口对象

from package.Utils.AdvancedSetWindow import MyAdvancedSetWindow
myAdvancedsetwin = MyAdvancedSetWindow()  # 实例化 MyAdvancedSetWindow 类，创建MyAdvancedSetWindow窗口对象